import cv2
import numpy as np
from matplotlib import pyplot as plt
import math

img = cv2.imread('sudoku.png',0)

# ======== cnn
kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
kernel_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
kernel_l = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]])

def convoluation(image, kernel):
    rows, cols = image.shape
    conv = np.zeros((rows - 2, cols - 2))
    for i in range(rows - 2):
        for j in range(cols - 2):
            img_array = np.array(image[i:i + 3, j:j + 3])
            conv[i, j] = np.sum(img_array * kernel)
    return conv

if __name__ == '__main__':
    res_x = convoluation(img, kernel_x)
    res_y = convoluation(img, kernel_y)
    res_l = convoluation(img, kernel_l)
    images = [img, res_x, res_y, res_l]

    titles = ['Original', 'x_gradient ', 'y_gradient', 'laplacian']

    for i in range(4):
        plt.subplot(2, 2, i + 1)
        plt.imshow(images[i], 'gray')
        plt.title(titles[i])
        plt.xticks([]), plt.yticks([])
    plt.show()
